# Goal: Describe the best combo of questions, and Create Table A8
# by Jennifer Pan and Yiqing Xu

### Install Packages
# install.packages("pheatmap")
# install.packages("coefficientalpha")
# install.packages("psych")
# install.packages("psy")

library(readr)
library(dplyr)

load("output/sample2_mi.RData")
load("output/s_bestset.RData")

# split qs into a list of 7 dims
qs <- read_csv("data/questions.csv", show_col_types = FALSE) 
sizes <- c(14, 14, 14, 7, 7, 7)
list_qs <- split(qs, rep(seq_along(sizes), times = sizes))


getComb <- function(out
  , dim # dimension of preferences
  , measure = "Pred"
  , min.Cronbach = 0.1
  , tol = 1 # tolerance for SumSign
  , top = 1) {
  result <- out$result
  comb <- out$comb
  sub <- which(result$Cronbach>=min.Cronbach & result$SumSign <= tol)
  result.sub <- out$result[sub,]
  if (measure == "Score") {
    output <- result.sub[order(result.sub$Score),]
  } else if (measure == "Pred") {
    output <- result.sub[order(result.sub$Pred, decreasing = TRUE),]
  } else if (measure == "Stab") {
    output <- result.sub[order(result.sub$Stab, decreasing = TRUE),]
  }
  cat("Top Combinations:\n")
  for (i in 1:top) {
    best <- comb[,output$id[i]]
    cat("No.", best, "\n\n")
    qs.sub <- list_qs[[dim]]
    print(as.data.frame(qs.sub[best, c("sign", "domain", "chn")]))
    cat("\n\n")
  }
  print(round(head(output[, c("Stab", "Pred")],top), 3))
}

getComb(out2, 2) # political
getComb(out3, 3) # economic
getComb(out1, 1) # nationalism
getComb(out4, 4) # traditional
getComb(out5, 5) # equality
getComb(out6, 6) # ethnicity
